package com.authine.cloudpivot.ext.controller.MatManage;

import cn.hutool.core.lang.Assert;
import com.authine.cloudpivot.engine.api.model.bizmodel.BizPropertyModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.Utils.Utils;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import javafx.application.Application;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/public/matManage")
@Slf4j
public class MatManageController extends BaseController {

    @Autowired
    CloudSqlService sqlService;

    @RequestMapping("/validSubmit")
    public ResponseResult validSubmit(@RequestBody Map<String,Object> map){

        return getOkResponseResult("");
    }


    /**
     *  物料管理表审批流完成后 数据写到总公司物料管理信息
     */
    @RequestMapping("finish")
    public void finish(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.MatManage, bizId);


        List<Map<String,Object>> list = (List<Map<String, Object>>) bizObject.get("SheetMatManage");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        //获取审批人

        String approval = getFileBaseInfoWorkFlowApproval(bizObject );


        for (Map<String, Object> map : list) {
            String MatCode = (String) map.get("txtMatCode");

            try {

                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(map);
//                String id = existsBizObject("txtMatCode",txtMatCode,CustomSchemaCode.CorpMatManageBase);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.CorpMatManageBase, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-公司职能  添加成功 ");
                //调用存储过程
                callProcess(id);

            } catch (Exception e) {
                log.info("基础表-公司职能  添加失败 funNumber={}", MatCode);
                log.info(e.getMessage(), e);
            }

        }
    }

    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map<String, Object> data) {

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CorpMatManageBase);

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where MatCode ='").append(data.get("txtMatCode"))
                .append("'; ");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     *  调用存储过程
     *
     *
     exec    SyncCorpMatManage
     @number    nvarchar(100),   ----物料编码
     @S01       NVARCHAR(100),   ----WD01
     @S02       NVARCHAR(100),   ----WD02
     @S03       NVARCHAR(100),   ----WD03
     @S04       NVARCHAR(100),   ----WD04
     @S05       NVARCHAR(100),   ----WD05
     @S06       NVARCHAR(100),   ----WD06
     @S07       NVARCHAR(100),   ----WD07
     @S08       NVARCHAR(100),   ----WD08
     @S09       NVARCHAR(100),   ----WD09
     @S10       NVARCHAR(100),   ----WD10
     @AuditDate  nvarchar(50)
     *
     *
     * @param bizId
     */
    private void callProcess(String bizId){

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CorpMatManageBase);
        StringBuilder sql = new StringBuilder("SELECT MatCode,MatName,Model,S01,S02,S03,S04,S05,S06,S07,S08,S09,S10,auditDate from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}",map);

        //调用存储过程


        String MatCode = MapUtils.getString(map,"MatCode","");
        String MatName = MapUtils.getString(map,"MatName","");
        String Model = MapUtils.getString(map,"Model","");
        String S01 = MapUtils.getString(map,"S01","");
        String S02 = MapUtils.getString(map,"S02","");
        String S03 = MapUtils.getString(map,"S03","");
        String S04 = MapUtils.getString(map,"S04","");
        String S05 = MapUtils.getString(map,"S05","");
        String S06 = MapUtils.getString(map,"S06","");
        String S07 = MapUtils.getString(map,"S07","");
        String S08 = MapUtils.getString(map,"S08","");
        String S09 = MapUtils.getString(map,"S09","");
        String S10 = MapUtils.getString(map,"S10","");
        String auditDate = MapUtils.getString(map,"auditDate","");

        String auditor = MapUtils.getString(map,"auditer","");


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncCorpMatManage  '%s','%s','%s','%s','%s','%s' ,'%s','%s','%s','%s','%s','%s' ",
                MatCode,S01,S02,S03,S04,S05,S06,S07,S08,S09,S10,auditDate);

        log.info("\n==========准备调用存储过程:{}",execSql);

        sqlService.execute(CloudSqlService.htEas,execSql);

        log.info("\n=============存储过程执行完成");

    }

    /**
     *  查询审批人,返回  员工号+姓名
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject ) {

        String activityCode="Activity15";
        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = activityCode;
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append(user.getName()).toString();
    }


    /**
     *  转换成  基础表-总公司物料管理信息 的数据
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String,Object> fileInfoBaseMap(Map<String,Object> map,String auditDate,String auditer){

        Map<String, Object> data = new HashMap<>();
        //编码
        data.put("MatCode", map.get("txtMatCode"));
        //名称
        data.put("MatName",map.get("MatName"));
        //型号示例
        data.put("Model",map.get("ModelExample"));
        //01 生产
        data.put("S01",map.get("S01"));
        //02 检测、验收
        data.put("S02",map.get("S02"));
        //03 日常管理
        data.put("S03",map.get("S03"));
        //04 委外、仓储
        data.put("S04",map.get("S04"));
        //05 租入、换入
        data.put("S05",map.get("S05"));
        //06 采购、期货
        data.put("S06",map.get("S06"));
        //07 销售
        data.put("S07",map.get("S07"));
        //08 受托、营储
        data.put("S08",map.get("S08"));
        //09 租出、换出
        data.put("S09",map.get("S09"));
        //10 回收
        data.put("S10",map.get("S10"));


        //审批人
//        data.put("auditer",auditer);

        return data;
    }


}
